/*
 * Copyright (C) 2014 Administrator
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package cn.ratking.demo.jaws6.security.view;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.omnifaces.util.Messages;
import org.slf4j.Logger;

import cn.ratking.demo.jaws6.model.User;
import cn.ratking.demo.jaws6.system.service.UserService;

@Named
@RequestScoped
/**
 * 注册用户
 */
public class RegisterUser {

    @Inject
    private transient Logger log;
    @Inject
    private UserService service;
    private User user;

    @PostConstruct
    public void init() {
        user = new User();
    }

    public User getUser() {
        return user;
    }

    public void submit() {
        try {
            user.setSalt(new Sha256Hash(user.getUsername()).toHex());
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
            service.create(user);
            log.debug("Registration suceed, new user ID is: {}", user.getUserId());
            Messages.addGlobalInfo("Registration suceed, new user ID is: {0}", user.getUserId());
        } catch (RuntimeException e) {
            log.error("Registration failed: {}", e.getMessage());
            Messages.addGlobalError("Registration failed: {0}", e.getMessage());
        }
    }

    public void doSomethingWhichIsOnlyAllowedByADMIN() {
        SecurityUtils.getSubject().checkRole("ADMIN");
        // ...
        log.debug("Debug: RegisterUser.doSomethingWhichIsOnlyAllowedByADMIN()");
    }
}
